<template>
  <div class="content-wrap content-container" v-loading="loading">
    <!-- 搜索区域 -->
    <el-form class="search-wrap" v-model="searchFormData">
      <el-form-item class="search-wrap-item" label="标题关键字：" prop="projectTitle">
        <el-input min-width="160px" placeholder="请输入标题关键字" v-model="searchFormData.projectTitle" clearable
          @input="getAllRequirements"></el-input>
      </el-form-item>
      <el-form-item class="search-wrap-item" label="时间：" prop="time">
        <el-date-picker style="width: 240px" type="daterange" unlink-panels range-separator="-" start-placeholder="开始时间"
          end-placeholder="结束时间" :value-on-clear="null" v-model="searchFormData.time" @change="getAllRequirements" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="createRequirementClick">创建需求</el-button>
      </el-form-item>
    </el-form>

    <!-- [我负责的需求]列表区域 -->
    <div class="card-layout-box">
      <div class="card-not-requirement" v-if="allRequirements.length === 0">暂无数据</div>
      <!-- 分类 -->
      <div v-if="allRequirements.length !== 0" class="card-box" v-for="(list, index) in allRequirements"
        :key="index">
        <div class="card-header-box" :style="{ backgroundColor: fatherStatus(list.status)?.bgColor }">
          <div>
            {{ fatherStatus(list.status).text }}:{{ list.total }}
          </div>
          <!-- <div v-if="list.status === 7">
            <el-button size="small">未评分</el-button>
          </div> -->
        </div>
        <!-- 需求列表 -->
        <div class="card-list-box">
          <ul class="card-list">
            <li class="card-list-item" v-for="item in list.requirements" :key="item.ID">
              <!-- 需求标题 -->
              <div>
                <el-text class="w-150px mb-2 card-header-title" truncated tag="b" @click="handleRowClick(item.ID)">
                  {{ item.requirementName }}
                </el-text>
              </div>

              <!-- 第二行 -->
              <div class="card-list-small">
                <!-- 任务附加信息 -->
                <div class="card-small">
                  <div class="card-list-small-item boss-name" v-if="item.requirementAuditName">审核人：{{ item.requirementAuditName }}</div>
                  <div class="card-list-small-item boss-name"  v-if="item.requirementBossName">技术负责人：{{ item.requirementBossName == "" ? "无" :
                    item.requirementBossName }}</div>
                  <div class="card-list-small-item test-list" v-if="item.requirementRelevances">参与研发：{{ item.requirementRelevances }}</div>
                  <div class="card-list-small-item test-list"
                     v-if="(userAuthId == '111' || userAuthId == '888' || userAuthId == '999') && item.requirementFatherStatus !== 1 && item.requirementFatherStatus < 4" 
                     :style="{ color: (item.contactTestNames == '' || item.contactTestNames.replace(/\|/g, '') == '') ? '#DF0101' : 'black' }"
                    >
                     {{ (item.contactTestNames == '' || item.contactTestNames.replace(/\|/g, '') == '') ? '未分配测试' : `参与测试：${item.contactTestNames}`  }}
                  </div>
                  <!-- 研发评论 -->
                  <div class="card-list-small-item" v-if="userAuthId == '555' && item.requirementFatherStatus == 8">
                    <span :style="{color: item.requirementOnlineStatus == 3 ? 'red' : 'green'}">{{ item.requirementOnlineStatus == 2 ? '上线成功' : '上线失败' }} / </span>
                    <span :style="{color: item.tipDevOnlineStatus == 1 ? 'red' : 'green'}">{{ item.tipDevOnlineStatus == 1 ? '未评论' : '已评论' }}</span>
                  </div>
                  <!-- 测试评论 -->
                  <div class="card-list-small-item" v-if="userAuthId == '111' && item.requirementFatherStatus == 8" :style="{color: item.tipTsOnlineStatus == 1 ? 'red' : 'green'}">
                    <span :style="{color: item.requirementOnlineStatus == 3 ? 'red' : 'green'}">{{ item.requirementOnlineStatus == 2 ? '上线成功' : '上线失败' }} / </span>
                    <span :style="{color: item.tipTsOnlineStatus == 1 ? 'red' : 'green'}">{{ item.tipTsOnlineStatus == 1 ? '未评论' : '已评论' }}</span>
                  </div>
                  <div class="card-list-small-item begin-time">创建日期：{{ tableTimeDate(item.beginTime) }}</div>
                </div>

                <!-- 操作 -->
                <div class="operate-box">
                  <el-dropdown :hide-on-click="false" placement="bottom" @command="handleCommand">
                    <span class="el-dropdown-link">
                      <el-icon class="el-icon--right" color="#409EFF"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <!-- 研发负责人分配研发任务操作 -->
                        <el-dropdown-item 
                          v-if="item.requirementFatherStatus == 1 && (userAuthId == '555' || userAuthId == '888' || userAuthId == '999')" 
                          :command="{requirement:item, operate: fatherStatus(item.requirementFatherStatus).status}"
                        >
                          {{ item.itemRequirementWorldSummary == '' ? "上传概要设计" : fatherStatus(item.requirementFatherStatus).operate  }}
                        </el-dropdown-item>
                        
                        <!-- 如果用户为测试负责人,分配测试人员 -->
                        <el-dropdown-item 
                          v-if="(userAuthId == '111') && (item.contactTestNames == '' || item.contactTestNames == '|') && (item.requirementFatherStatus < 4)" 
                          :command="{requirement:item, operate: 1}"
                        >
                          {{ fatherStatus(1).operate }}
                        </el-dropdown-item>

                          <!-- 研发负责人提交上线结果 -->
                         <el-dropdown-item v-if="userAuthId == '555' && item.requirementFatherStatus == 7" :command="{requirement: item, operate: 7}">
                          {{ fatherStatus(item.requirementFatherStatus).operate }}
                         </el-dropdown-item>

                        <!-- 研发负责人对上线研发和运维的评语 -->
                         <el-dropdown-item v-if="item.requirementFatherStatus == 8 && userAuthId == '555'" :command="{requirement: item, operate: 8}">
                          {{ item.tipDevOnlineStatus == 1 ? fatherStatus(item.requirementFatherStatus).operate : '查看'}}
                         </el-dropdown-item>

                        <!-- 测试负责人对上线研发和运维的评语 -->
                         <el-dropdown-item v-if="item.requirementFatherStatus == 8 && userAuthId == '111'" :command="{requirement: item, operate: 8}">
                          {{ item.tipTsOnlineStatus == 1 ? fatherStatus(item.requirementFatherStatus).operate : '查看'}}
                         </el-dropdown-item>

                        <!-- 如果用户为测试人员，测试中操作 -->
                        <el-dropdown-item 
                          v-if="(userAuthId == '666' || userAuthId == '111') && item.requirementFatherStatus > 4 && item.requirementFatherStatus < 8" 
                          :command="{requirement:item, operate: fatherStatus(item.requirementFatherStatus).status}"
                        >
                          {{ fatherStatus(item.requirementFatherStatus).operate  }}
                        </el-dropdown-item>

                        <!-- 已关闭的需求撤回操作 -->
                        <el-dropdown-item 
                          v-if="item.requirementFatherStatus == 9" 
                          :command="{requirement:item, operate: 9}"
                        >
                          {{ fatherStatus(item.requirementFatherStatus).operate  }}
                        </el-dropdown-item>

                        <el-dropdown-item v-if="item.requirementFatherStatus !== 9 && item.requirementFatherStatus !== 8" :command="{requirement:item, operate: 9}">关闭</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 上传概要设计 -->
    <el-dialog
      class="dialog-container"
      style="
        min-height: 400px;
        display: flex;
        justify-content: space-between;
        flex-direction: column;
      "
       :close-on-click-modal="false"
      v-model="dialogDesignFileVisible"
      title="上传概要设计"
      @close="handleCloseDialog"
      @closed="handleCloseDialog"
    >
      <el-upload
        class="upload-demo"
        drag
        action=""
        multiple="true"
        :limit="1"
        v-model:file-list="designFileText"
        :http-request="handleUpLoad"
        :on-error="handleError"
        :on-remove = "handleRemove"
        :on-exceed = "handleExceed"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          Drop file here or <em>click to upload</em>
        </div>
      </el-upload>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleDesignFile(isRequirementID)">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 对项目经理评语弹窗 -->
    <el-dialog
    class="dialog-container"
      style="
        min-height: 400px;
        display: flex;
        justify-content: space-between;
        flex-direction: column;
      "
      v-model="dialogIsGetTestVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      title="请对项目经理进行评分："
    > 
    <el-form>
        <el-form-item label="评语：">
          <el-input
            maxlength="200"
            placeholder="请输入评语..."
            show-word-limit
            type="textarea"
            v-model="requirementMsg"
          />
        </el-form-item>
        <el-form-item label="评分：">
          <el-input-number
            style="width: 100px;"
            class="mx-4"
            min="0"
            max="500"
            controls-position="right"
            v-model="reViewContentNumber"
          />
        </el-form-item>
      </el-form>
     
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitIsGetTest">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配任务弹窗 -->
    <el-dialog
      class="dialog-container"
      style="
        min-height: 400px;
        max-height: 700px;
        display: flex;
        justify-content: space-between;
        flex-direction: column;
        flex-wrap: nowrap;
      "
      width="1200px"
      :close-on-click-modal="false"
      v-model="dialogAvgVisible"
      title="分配任务"
      @close="handleCloseAssDialog"
      @closed="handleCloseAssDialog"
    >
      <!-- 研发负责人分配研发人员 -->
      <div style="overflow-y: auto; max-height: 580px;" v-if="(userAuthId == '555' || userAuthId == '888' || userAuthId == '999')">
        <!-- 分配研发人员 -->
        <p class="dialog-form-title">参与研发人员：</p>
        <el-form
          class="dialog-form-box"
          :model="avgRequirementFormData"
          v-for="(item, index) in avgRequirementFormData"
          :key="index"
        >
          <!-- 研发人员 -->
          <el-form-item prop="userUUID">
            <el-select
              v-model="item.userUUID"
              filterable
              placeholder="参与人员"
              style="width: 100px"
              clearable
            >
              <el-option
                v-for="test in allDevNameOptions"
                :key="test.uuid"
                :label="test.nickName"
                :value="test.uuid"
                :disabled="isDisabled(test.uuid, item.userUUID, 1)"
              />
            </el-select>
          </el-form-item>
          <!-- 预计完成时间 -->
          <el-form-item prop="guessTime">
            <el-date-picker
              style="width: 140px"
              v-model="item.guessTime"
              type="date"
              placeholder="预计完成时间"
              :disabledDate="disabledDate"
            />
          </el-form-item>
          <!-- 描述工作内容 -->
          <el-form-item prop="processJob">
            <el-input
              style="width: 420px"
              placeholder="简述工作内容..."
              clearable
              v-model="item.processJob"
            ></el-input>
          </el-form-item>
          <!-- 评估耗时 -->
          <el-form-item prop="guessProcess">
            耗时：
            <el-input-number
              style="width: 80px"
              v-model="item.guessProcess"
              :min="1"
              controls-position="right"
            />
            &nbsp;&nbsp;小时
          </el-form-item>
          <!-- 需求评分 -->
          <el-form-item prop="processJobNum">
            评分：
            <el-input-number
              style="width: 80px"
              v-model="item.processJobNum"
              :min="0"
              :max="500"
              controls-position="right"
            />
          </el-form-item>
          <!-- 新增/删除操作按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              plain
              size="small"
              @click="handleAddFormData(1)"
              ><el-icon :size="14"><Plus /></el-icon
            ></el-button>
            <el-button
              type="danger"
              plain
              size="small"
              @click="handleDelFormData(index, 1)"
              ><el-icon :size="14"><Minus /></el-icon
            ></el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 测试负责人分配测试人员 -->
      <div style="overflow-y: auto; max-height: 580px;" v-if="(userAuthId == '111')">
        <!-- 分配测试人员 -->
        <p class="dialog-form-title">参与测试人员：</p>
        <el-form
          class="dialog-form-box"
          :model="tsRequirementFormData"
          v-for="(item, index) in tsRequirementFormData"
          :key="index"
        >
          <!-- 测试人员 -->
          <el-form-item prop="userUUID">
            <el-select
              v-model="item.userUUID"
              filterable
              placeholder="参与人员"
              style="width: 100px"
              clearable
            >
              <el-option
                v-for="test in allTestNameOptions"
                :key="test.uuid"
                :label="test.nickName"
                :value="test.uuid"
                :disabled="isDisabled(test.uuid, item.userUUID, 2)"
              />
            </el-select>
          </el-form-item>
          <!-- 预计完成时间 -->
          <el-form-item prop="guessTime">
            <el-date-picker
              style="width: 140px"
              v-model="item.guessTime"
              type="date"
              placeholder="预计完成时间"
              :disabledDate="disabledDate"
            />
          </el-form-item>
          <!-- 描述工作内容 -->
          <el-form-item prop="processJob">
            <el-input
              style="width: 420px"
              placeholder="简述工作内容..."
              clearable
              v-model="item.processJob"
            ></el-input>
          </el-form-item>
          <!-- 评估耗时 -->
          <el-form-item prop="guessProcess">
            耗时：
            <el-input-number
              style="width: 80px"
              v-model="item.guessProcess"
              :min="1"
              controls-position="right"
            />
            &nbsp;&nbsp;小时
          </el-form-item>
          <!-- 需求评分 -->
          <el-form-item prop="processJobNum">
            评分：
            <el-input-number
              style="width: 80px"
              v-model="item.processJobNum"
              :min="0"
              :max="500"
              controls-position="right"
            />
          </el-form-item>
          <!-- 新增/删除测试操作按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              plain
              size="small"
              @click="handleAddFormData(2)"
              ><el-icon :size="14"><Plus /></el-icon
            ></el-button>
            <el-button
              type="danger"
              plain
              size="small"
              @click="handleDelFormData(index, 2)"
              ><el-icon :size="14"><Minus /></el-icon
            ></el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作区域 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfirmAvg">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 技术负责人填写上线结果 -->
    <el-dialog class="dialog-container" style="width: 800px;" v-model="dialogOfflineToEndVisible" title="上线结果"  :close-on-click-modal="false" @close="handleCloseOnlineDialog" @closed="handleCloseOnlineDialog">
      <el-form ref="offlineToEndFomrRef" :rules="offlineToEndFormRules" :model="offlineToEndForm">
        <el-form-item label="上线结果：" porp="requirementOnlineStatus">
          <el-radio-group v-model="offlineToEndForm.requirementOnlineStatus" size="small">
            <el-radio :value="2" border>成功</el-radio>
            <el-radio :value="3" border>失败</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="offlineToEndForm.requirementOnlineStatus == 3" label="不通过的原因：" :required="offlineToEndForm.requirementOnlineStatus == 3" porp="requirementOnlineMsg">
          <el-input
            maxlength="500"
            placeholder="请输入上线不通过的原因"
            show-word-limit
            type="textarea"
            :rows="10"
            v-model="offlineToEndForm.requirementOnlineMsg"
          />
        </el-form-item>
        <el-form-item>
          <div class="dialog-footer">
            <el-button type="defalut" @click="handleCloseOnlineDialog">取消</el-button>
            <el-button type="primary" @click="handleSubmitOffline()">确定</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 技术负责人/测试负责人对上线参与人评价 -->
    <el-dialog class="dialog-online-container" style="width: 800px;max-height: 680px; margin-top: 50px;overflow-y: auto;" :close-on-click-modal="false" v-model="dialogOfflineEndCotentVisible" title="查看" @close="handleCloseOnlineContentDialog" @closed="handleCloseOnlineContentDialog">
      <!-- <el-form :model="offlineToEndContentForm" ref="offlineToEndContentFormRef" :rules="offlineToEndContentFormRules">
        <ul>
          <li v-for="(item, index) in offlineToEndContentForm" :key="item.ID">
            <div>
              <span>{{ bearStatus(item.bearType)?.text }}参与人:</span>
              <p>{{ item.bearUserName }}</p>
            </div>
            <div>
              <span>任务内容：</span>
              <p>{{ item.bearContent }}</p>
            </div>
            <el-form-item label="评语：" :prop="`offlineToEndContentForm.${index}.bearBossContent`" :rules="itemRules.bearBossContent" trigger="blur">
              <el-input v-model="offlineToEndContentForm[index].bearBossContent"></el-input>
            </el-form-item>
            <el-form-item label="评分：" :prop="`offlineToEndContentForm.${index}.bearBossUserTPNumber`" :rules="itemRules.bearBossUserTPNumber" trigger="blur">
              <el-input v-model.number="offlineToEndContentForm[index].bearBossUserTPNumber"></el-input>
            </el-form-item>
          </li>
        </ul>
        <el-button type="primary" @click="submitOnlineToEndForm">提交</el-button>
      </el-form> -->
      <div class="online-outcome">
        <p class="online-outcome-top">上线结果：{{ isRequirementData.requirementOnlineMsg == '' ? '成功' : '失败' }}</p>
        <p v-if="isRequirementData.requirementOnlineMsg !== ''">失败原因：
          <span>{{ isRequirementData.requirementOnlineMsg }}</span>
        </p>
      </div>
      <div v-if="offlineToEndContentForm.length == 0" style="color: red;">无人参与，无须评价</div>
      <div class="online-box" v-if="offlineToEndContentForm.length > 0">
        <el-form class="online-form-box" :model="offlineToEndContentForm">
          <ul class="online-form-ul">
            <li class="online-form-li" v-for="(item, index) in offlineToEndContentForm" :key="item.ID">

              <div class="online-form-content online-form-content-top">
                <div class="online-form-info online-form-info-left">
                  <p>{{ bearStatus(item.bearType)?.text }}参与人：</p>
                  <p>{{ item.bearUserName }}</p>
                </div>
                <div class="online-form-info online-form-info-right">
                  <p class="online-info-title">任务内容：</p>
                  <el-input class="online-content-box" disabled v-model="item.bearContent"></el-input>
                </div>
              </div>

              <div class="online-form-content">
                <el-form-item class="online-form-info-left" label="评分：" :prop="`offlineToEndContentForm.${index}.bearBossUserTPNumber`">
                  <el-input-number size="defalut" :disabled="!isOnlineContent" v-model.number="offlineToEndContentForm[index].bearBossUserTPNumber"></el-input-number>
                </el-form-item>
                <el-form-item class="online-form-info-right" size="samll" label="上线评语：" :prop="`offlineToEndContentForm.${index}.bearBossContent`">
                  <el-input type="textarea" :rows="2" v-model="offlineToEndContentForm[index].bearBossContent" placeholder="请对上线参与人写下评语" clearable :disabled="!isOnlineContent"></el-input>
                </el-form-item>
              </div>
            </li>
          </ul>
        </el-form>
        <div class="online-operate" v-if="isOnlineContent">
          <el-button type="defalut" @click="handleCloseOnlineContentDialog">取消</el-button>
          <el-button type="primary" @click="submitOnlineToEndForm">提交</el-button>
        </div>
      </div>

    </el-dialog>

    <!-- 需求详情弹窗 -->
    <el-dialog v-if="dialogInfoVisible" style="width: 1200px;" :close-on-click-modal="false" v-model="dialogInfoVisible" @close="handleCloseDialog" @closed="handleCloseDialog">
        <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="clearData"></CommonRequirementInfoVue>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, FormInstance  } from "element-plus";
import { ElForm } from "element-plus";
import {
  postAvgRequirement, putCloseRequirementStatus, getNewFatherRequirementStatus,
  postInitRequirement, PostOfflineToEnd, GetGetBareUsersMsgs, PutOnlineEndBearContents, 
  PutReturnCloseFatherRequirementStatus,
} from "@/api/newDemands/index";
import { postUploadFile } from "@/api/common/index";
import { handleUploadRequirement, handleUpdateGetTest } from "@/utils/common";
import { tableTimeDate, fatherStatus, isValidateString, bearStatus} from "@/utils/utils";
import useCommonDataStore from "@/store/common/common";
import CommonRequirementInfoVue from "../comomRequirementInfo.vue";

let router = useRouter();
let useCommonStore = useCommonDataStore();
const loading = ref(false);
const userAuthId = ref<any>(null);//当前用户权限id
const allRequirements = ref<any>([]); // 我负责的所有需求
const summaryPaths = ref<any>([]);//该需求所有的需求草稿地址
const baseUrl = ref(import.meta.env.VITE_SERVE);//服务器地址
const searchFormData = ref({
  projectTitle: "",
  time: [null, null]
});

const dialogAvgVisible = ref(false); //控制是否开启分配任务弹窗
const dialogCloseVisible = ref(false); //控制是否关闭任务弹窗
const dialogInfoVisible = ref(false);//查看需求弹窗控件
const clearData = ref(false);//控制是否清空子组件数据
const dialogRecordVisible = ref(false);//控制查看审核记录弹窗控件
const dialogDesignFileVisible = ref(false);//控制上传概要设计控件
const dialogIsGetTestVisible = ref(false);//控制是否需要对项目经理进行评论
const dialogTestResultVisible = ref(false);//控制测试是否通过弹窗控件
const dialogOfflineToEndVisible = ref(false);//控制上线结果弹窗控件
const dialogOfflineEndCotentVisible = ref(false);//控制上线评论弹窗控件


const isAvgRequirementID = ref(); //当前操作任务ID
const isRequirementID = ref(); //当前操作任务ID
const isRequirementData = ref<any>(null);//当前需求数据
const allDevNameOptions = ref(); //所有研发人员列表
const allTestNameOptions = ref(); //所有测试人员列表
const designFileText = ref([]);//概要设计文件显示
const designFilePath = ref("");//概要设计文件地址
const isGetTest = ref(2);//判断当前需求是否需要测试参与
const requirementMsg = ref(""); //评语
const reViewContentNumber = ref<any>(null);//评分
const recordData = ref<any>([]);//所有审核记录

const avgRequirementFormData = reactive<any>([
  {
    userUUID: "",
    guessTime: "",
    processJob: "",
    guessProcess: 1,
    processJobNum: 100,
  },
]); // 已分配研发人员列表
const tsRequirementFormData = reactive<any>([
  {
    userUUID: "",
    guessTime: "",
    processJob: "",
    guessProcess: 1,
    processJobNum: 100,
  },
]); // 已分配测试人员列表


/* 测试中 */
/* //* 测试通过-对研发评论
const showTipCTOYRef = ref<FormInstance>();//测试通过表单实例
// 测试通过-对研发评论的表单校验规则
const showTipCTOYRules = reactive({
  itemRequirementCTOYTip: [{
    required: true,
    message: "必填", 
    trigger: "blur", 
    validator: (rule: any, value: any, callback: any) => {
        // 调用自定义验证函数
        if (isValidateString(value)) {
          callback(new Error("需求详情不能为空格或空行！"));
        } else {
          callback();
        }
      }
  }],
  itemRequirementCTOYNumber: [{
    required: true,
    message: "必填", 
    trigger: "blur", 
  }],
});
// 测试通过-对研发评论表单数据
const showTipCTOYForm = ref<any>({
    childChildIdId: null,
    itemRequirementCTOYTip: "",
    itemRequirementCTOYNumber: 100
});

//* 测试不通过-提交bug列表
const testFaliedBugForm = ref<any>({
  childChildId: null,
  bugIds: []
}); */

// * 技术负责人提交上线结果
const offlineToEndFomrRef = ref<FormInstance>();//技术负责人提交上线结果表单实例
const isOfflineToEnd = ref(false);// 上线是否通过
// 上线结果表单校验规则
const offlineToEndFormRules = reactive({
  requirementOnlineMsg: [
    { 
      required: isOfflineToEnd.value,
      message: "必填", 
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        console.log(value);
        if (isValidateString(value)) {
          callback(new Error("必填，且不能为空格或空行！"));
        } else {
          callback();
        }
      },
    }
  ]
});
// 上线结果表单数据
const offlineToEndForm = ref<any>({
  requirementId: null,
  requirementOnlineStatus: 2,
  requirementOnlineMsg:""
});

// * 上线评分
// const offlineToEndBears = ref<any>([]);
// const offlineToEndContentFormRef = ref<any>();
// const offlineToEndContentFormRules = {
//   'offlineToEndContentForm': [
//     {
//       required: true,
//       message: '至少填写一条记录',
//       trigger: 'blur',
//       validator: (rule: any, value: any, callback: any) => {
//         console.log("表单数据：", value);
//         if (value.length === 0) {
//           callback(new Error('至少填写一条记录'));
//         } else {
//           const valid = value.every((item:any) => {
//             const contentValid = item.bearBossContent && item.bearBossContent.trim() !== '';
//             const scoreValid = !isNaN(item.bearBossUserTPNumber) && item.bearBossUserTPNumber >= 0 && item.bearBossUserTPNumber <= 100;
//             return contentValid && scoreValid;
//           });
//           if (!valid) {
//             callback(new Error('每条记录必须有评语和评分'));
//           } else {
//             callback();
//           }
//         }
//       }
//     }
//   ]
// };

// const itemRules = {
//   bearBossContent: [
//     { 
//       required: true,
//       message: '必填', 
//       trigger: 'blur', 
//       // validator: (rule: any, value: any, callback: any) => {
//       //   if (isValidateString(value)) {
//       //     callback(new Error("必填，且不能为空格或空行！"));
//       //   } else {
//       //     callback();
//       //   }
//       // }
//     },
//   ],
//   bearBossUserTPNumber: [
//     { required: true, message: '评分不能为空', trigger: 'blur' },
//     { type: 'number', message: '评分必须是数字', trigger: 'blur' },
//     { min: 0, max: 100, message: '评分在 0 到 100 之间', trigger: 'blur' }
//   ]
// };

const offlineToEndContentForm = ref<any>([]);// 上线评分提交数据
const isOnlineContent = ref(true);// 是否提交评论：true-提交；false-查看




// TODO 点击创建任务
const createRequirementClick = () => {
  router.push({
    path: "/requirement/create",
  });
};


// TODO 获取用户负责的所有需求
const getAllRequirements = async () => {
  loading.value = true;
  userAuthId.value = localStorage.getItem("authorityId");
  console.log(userAuthId.value)
  console.log("搜索条件：", searchFormData.value);

  const { data } = await postInitRequirement({
    projectTitle: searchFormData.value.projectTitle,
    beginTime: searchFormData.value.time === null ? null : searchFormData.value.time[0],
    endTime: searchFormData.value.time === null ? null : searchFormData.value.time[1]
  });

  if (data.code === 200) {
    if (data.data.requirements === null) {
      allRequirements.value = [];
      loading.value = false;
      return;
    } else {
      allRequirements.value = data.data.requirements;

      if (allRequirements.value.length > 0) {
        // 1、将响应数据根据requirementFatherStatus进行分类并统计
        const statusCount = {} as any;

        allRequirements.value.forEach((item: any) => {
          let fatherStatus = item.requirementFatherStatus;

          if (statusCount[fatherStatus]) {
            statusCount[fatherStatus].total++;
            // 判断该item是否已经添加
            if (!statusCount[fatherStatus].requirements.includes(item.ID)) {
              statusCount[fatherStatus].requirements.push(item);
            }
          } else {
            statusCount[fatherStatus] = {
              status: Number(fatherStatus),
              total: 1,
              requirements: [item]
            }
          }
        });

        allRequirements.value = Object.values(statusCount);
        loading.value = false;
      }
      loading.value = false;
      console.log("我负责的所有需求：",allRequirements.value)
    }
  } else {
    ElMessage.error(data.msg);
    loading.value = false;
    return;
  };

  loading.value = false;
};

// 查看需求
const handleRowClick = async (id: number) => {
  console.log("查看需求:", id);
  dialogInfoVisible.value = true;
  isRequirementID.value = id;
};


// ! 操作
const handleCommand = async (val: any) => {
  isRequirementID.value = val.requirement.ID;
  isRequirementData.value = val.requirement;
  console.log("当前操作需求：", isRequirementData.value);

  switch (val.operate) {
    case 1:
      /* 研发负责人先上传概要设计，再判断是否需要测试参与 */
      // 如果已经上没有上传设计概要，则先上传设计概要
      if(val.requirement.itemRequirementWorldSummary == '' && userAuthId.value !== '111') {
        dialogDesignFileVisible.value = true;
      } else {
        dialogAvgVisible.value = true;
      };
      // 如果用户为研发负责人
      if (userAuthId.value !== '111') {
        await useCommonStore.getAllRoleUsersList("555|777|999");
        allDevNameOptions.value = useCommonStore.$state.allRoleUserList;
      } else {
        // 如果用户为测试负责人
        await useCommonStore.getAllRoleUsersList("666|111");
        allTestNameOptions.value = useCommonStore.$state.allRoleUserList;
      }
      break;
    // case 2:
    //  ElMessage.info("开发需求");
    //   break;
    // case 3:
    //  ElMessage.info("提测需求");
    //   break;
    // case 4:
    //  ElMessage.info("审核中");
    //   break;
    case 5:
      ElMessage.info("测试中-是否通过");
      dialogTestResultVisible.value = true;
      break;
    case 6:
      ElMessage.info("待上线评审");
      break;
    case 7:
      ElMessage.info("待上线");
      offlineToEndForm.value.requirementId = isRequirementID.value;
      dialogOfflineToEndVisible.value = true;
      break;
    case 8:
      ElMessage.info("已上线");
      await handleOpenOfflineToEndContent(isRequirementID.value);
      break;
    case 9:
      if(isRequirementData.value.requirementFatherStatus < 8) {
        // 关闭fatherStatus
        ElMessage.info("关闭需求！");
        await closeFatherStatus(val.requirement.ID);
      } else if (isRequirementData.value.requirementFatherStatus == 9) {
        // 撤回已关闭需求
        console.log("撤回");
        await returnFatherStatus(val.requirement.ID);
      }
      break;
    default:
      await closeFatherStatus(val.requirement.ID);
      break;
  }
};

// TODO 分配需求

//  自定义上传文件
const handleUpLoad = async (options: any) => {
  console.log("Options:", options);

  const { data } = await postUploadFile(options.file, "summaryWorld", "2");
  if(data.code === 200) {
    // 文件地址
    designFilePath.value = data.data.resultFilePath;
  } else {
    ElMessage.error(data.msg);
    throw console.error(data.msg);
  }
};


// const handleSuccess = (v: any) => {
//   // 文件地址
//   designFilePath.value = v.data.data.resultFilePath;
//   console.log("文件地址：", designFilePath.value);
// };

const handleError = (err: any) => {
  ElMessage.error(err);
};

const handleRemove = (file: any) => {
  designFileText.value = [];
  designFilePath.value = "";
};

const handleExceed = (exc: any) => {
  ElMessage.warning("只能上传1个文件！")
};

// 上传概要设计后将文件与需求绑定
const handleDesignFile = async (id: number) => {
  dialogDesignFileVisible.value = true;
  if(designFilePath.value == "") {
    ElMessage.warning("必须上传详细设计");
    return;
  } else {
    await handleUploadRequirement({
      itemRequirementId: id,
      fileType: 2,
      draftPath: null,
      summaryPath: designFilePath.value,
      detailedPath: null,
      meetingPath: null,
      onLineMeetingPath: null
    }).then(async () => {
      // 判断是否需要测试参与
      await handleGetTest();
      console.log("评分前isGetTest值：", isGetTest.value);

    
      // 判断是否需要对项目经理评分
      if(isRequirementData.value.requirementCreateName !== isRequirementData.value.requirementBossName) {
        dialogDesignFileVisible.value = false;
        dialogIsGetTestVisible.value = true;
    
        loading.value = true;
        await getAllRequirements();
        loading.value = false;
    
      } else {
        dialogDesignFileVisible.value = false;
        dialogIsGetTestVisible.value = false;

        loading.value = true;
        await getAllRequirements();
        loading.value = false;

        dialogAvgVisible.value = true;
      }
    }).catch(() => {
      ElMessage.error("上传失败！");
      throw console.error();
    });
  }
};

// 判断是否需要测试参与
const handleGetTest = async () => {
 await  ElMessageBox.confirm("此需求是否需要测试参与？", "操作", {
  confirmButtonText: "需要",
  cancelButtonText: "不需要",
  type: "warning",
  closeOnClickModal: false, // 防止点击遮罩层关闭弹窗
  closeOnPressEscape: false, // 防止按下 Esc 键关闭弹窗
  showClose: false, // 隐藏右上角的关闭按钮
  }).then (async () => {
    // 需要测试参与
    isGetTest.value = 2;
    await handleUpdateGetTest({
      itemRequirementId: isRequirementID.value,
      isGetTest: 2,
      itemRequirementPMTip: "",
      itemRequirementPMNumber: null
    });
  })
  .catch (async () => {
    // 不需要测试参与
    isGetTest.value = 1;
    await handleUpdateGetTest({
      itemRequirementId: isRequirementID.value,
      isGetTest: 1,
      itemRequirementPMTip: "",
      itemRequirementPMNumber: null
    });
  });

  // 获取研发人员列表
  await useCommonStore.getAllRoleUsersList("555|777|999");
  allDevNameOptions.value = useCommonStore.$state.allRoleUserList;
  // isGetTest.value = isGetTest.value;
  console.log("窗口关闭时isGetTest值：", isGetTest.value);
};


// 提交对项目经理的评语及评分
const submitIsGetTest = async () => {
  console.log("对项目经理的评语和评分！");
  if(reViewContentNumber.value == null || requirementMsg.value.trim() == "") {
    ElMessage.warning("必须填写评语及评分");
    return;
  } else {
    console.log("提交评论时：", isGetTest.value);
    await handleUpdateGetTest({
        itemRequirementId: isRequirementID.value,
        isGetTest: isGetTest.value,
        itemRequirementPMTip: requirementMsg.value.trim(),
        itemRequirementPMNumber: reViewContentNumber.value
    })
    .then (() => {
      dialogIsGetTestVisible.value = false;
      reViewContentNumber.value = null;
      requirementMsg.value = "";

      dialogAvgVisible.value = true;
    }).catch((error) => {
      reViewContentNumber.value = null;
      requirementMsg.value = "";
      ElMessage.error("评分提交失败！");
      throw console.error(error);
    })
  }
};



// TODO 关闭主需求
const closeFatherStatus = async (val: any) => {
  console.log("关闭需求：", val);
  await ElMessageBox.confirm("确认关闭该需求吗？", {
    confirmButtonText: "确认"
  }).catch(() => {
    console.log("取消关闭该需求！");
    return new Promise(() => { });
  });

  const { data } = await putCloseRequirementStatus({
    requirementId: val
  });
  if (data.code !== 200) {
    ElMessage.warning(data.msg);
    return;
  } else {
    await getAllRequirements();
  }
};

// TODO 撤回需求
const returnFatherStatus = async (val: number) => {
  console.log("撤回需求：", val);
  await ElMessageBox.confirm("确认撤回该需求吗？", {
    confirmButtonText: "确认"
  }).catch(() => {
    console.log("取消撤回该需求！");
    return new Promise(() => { });
  });

  const { data } = await PutReturnCloseFatherRequirementStatus({
    requirementId: val
  });
  if (data.code !== 200) {
    ElMessage.warning(data.msg);
    return;
  } else {
    loading.value = true;
    await getAllRequirements();
    loading.value = false;
  }
};


// TODO 处理开发周期时间的方法
/* // const handleOnlineTime = (val: any) => {
//   if (val == null || val == "") {
//     return "";
//   } else {
//     return tableTimeDate(val);
//   }
// };

// TODO 鼠标右键事件
// const onRightClick = (event: MouseEvent, item: any) => {
//   // 阻止默认的右键事件
//   event.preventDefault();
//   // 阻止事件冒泡
//   event.stopPropagation();

//   // 自定义右键点击事件:显示操作按钮
//   item.isShowOperate = true;
// }; */

// TODO 新增分配人员行
const handleAddFormData = (val: any) => {
  if(val === 1) {
    avgRequirementFormData.push({
      userUUID: "",
      guessTime: "",
      processJob: "",
      guessProcess: 1,
      processJobNum: 100,
    });
    console.log("当前选中研发人：", avgRequirementFormData);
  };

  if(val === 2) {
    tsRequirementFormData.push({
      userUUID: "",
      guessTime: "",
      processJob: "",
      guessProcess: 1,
      processJobNum: 100,
    });
    console.log("当前选中测试人：", tsRequirementFormData);
  }
};
// TODO 删除分配人员行
const handleDelFormData = (index: number, del: number) => {
  switch (del) {
    // 分配前删除研发人员
    case 1:
      if(avgRequirementFormData.length === 1) {
          ElMessage.warning("需至少保留一项!");
          return;
        } else {
          avgRequirementFormData.splice(index, 1);
          return avgRequirementFormData;
      };
      // 分配前删除测试人员
    case 2:
      if(tsRequirementFormData.length === 1) {
        ElMessage.warning("需至少保留一项!");
        return;
      } else {
        tsRequirementFormData.splice(index, 1);
      }
  }
};
// TODO 规定预计上线时间为today及之后，之前的不可选
const disabledDate = (time: any) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

// TODO 关闭弹窗
const handleCloseDialog = () => {
  // isGetTest.value = undefined;

  avgRequirementFormData.length = 0;
  avgRequirementFormData.push({
    userUUID: "",
    guessTime: "",
    processJob: "",
    guessProcess: 1,
    processJobNum: 100,
  });

  tsRequirementFormData.length = 0;
  tsRequirementFormData.push({
    userUUID: "",
    guessTime: "",
    processJob: "",
    guessProcess: 1,
    processJobNum: 100,
  });

  isRequirementData.value = null;

  designFileText.value = [];
  designFilePath.value = "";
  dialogDesignFileVisible.value = false;

  
  dialogRecordVisible.value = false;
  recordData.value = [];
  
  clearData.value = true;
};

// TODO 关闭分配弹窗
const handleCloseAssDialog = () => {
  // isGetTest.value = 2;
  avgRequirementFormData.length = 0;
  avgRequirementFormData.push({
    userUUID: "",
    guessTime: "",
    processJob: "",
    guessProcess: 1,
    processJobNum: 100,
  });

  tsRequirementFormData.length = 0;
  tsRequirementFormData.push({
    userUUID: "",
    guessTime: "",
    processJob: "",
    guessProcess: 1,
    processJobNum: 100,
  });
  dialogAvgVisible.value = false;
}

// 分配研发人员动态添加禁选功能
const isDisabled = (testUuid: any, selectedUuid: any, val: number) => {
  if(val === 1) {
    // 检查当前测试人员UUID是否已经在avgRequirementFormData中被选中
    return avgRequirementFormData.some((formItem: any) => formItem.userUUID === testUuid && formItem.userUUID !== selectedUuid);
  } else {
    // 分配测试人员动态添加禁选功能
    // 检查当前测试人员UUID是否已经在tsRequirementFormData中被选中
    return tsRequirementFormData.some((formItem: any) => formItem.userUUID === testUuid && formItem.userUUID !== selectedUuid);
};
};


// 自定义验证函数
const validateFormData = () => {
  // 研发
  if(userAuthId.value == "555" || userAuthId.value == "888" || userAuthId.value == "999") {
    for (const item of avgRequirementFormData) {
      for (const value of Object.values(item)) {
        if (value === "" || value === null) {
          return {
            valid: false,
            message: "验证失败，所有字段均为必填项",
          };
        }
      }
    };
  };
  // 测试
  if(userAuthId.value == "111" || userAuthId.value == "888" || userAuthId.value == "999") {
    for (const item of tsRequirementFormData) {
      for (const value of Object.values(item)) {
        if (value === "" || value === null) {
          return {
            valid: false,
            message: "验证失败，所有字段均为必填项",
          };
        }
      }
    };
  };

  return {
    valid: true,
    message: "验证通过",
  };
};


// TODO 提交分配任务功能
const handleConfirmAvg = async () => {
  const result = computed(() => validateFormData()).value;

  if (result.valid) {
    console.log(result.message);

    // 研发
    if(userAuthId.value == "555" || userAuthId.value == "888" || userAuthId.value == "999") {
      tsRequirementFormData.length = 0;
      // 给每项添加userName
      avgRequirementFormData.forEach((item: any) => {
        item.userName = allDevNameOptions.value.find(
          (val: any) => val.uuid === item.userUUID
        ).nickName;
      });
      // 处理时间
      avgRequirementFormData.map(
        (item: any) => (item.guessTime = new Date(item.guessTime).toISOString())
      );
    };

    // 测试
    if(userAuthId.value == "111") {
      avgRequirementFormData.length = 0;
      // 给每项添加userName
      tsRequirementFormData.forEach((item: any) => {
        item.userName = allTestNameOptions.value.find(
          (val: any) => val.uuid === item.userUUID
        ).nickName;
      });
      // 处理时间
      tsRequirementFormData.map(
        (item: any) => (item.guessTime = new Date(item.guessTime).toISOString())
      );
    };


    let postFormData = {
      itemRequirementId: isRequirementID.value,
      devs: avgRequirementFormData,
      ts: tsRequirementFormData,
    };
    console.log("分配任务请求参数：", postFormData);

    // 1、发起分配需求请求
    const { data } = await postAvgRequirement(postFormData);
    if (data.code === 200) {
      // 2、请求成功后关闭弹窗并重新获取任务数据
      loading.value = true;
      dialogAvgVisible.value = false;
      
      if(userAuthId.value !== '111') {
        await updateFatherStatus(isRequirementID.value);
      };

      await getAllRequirements();
      loading.value = false;
    } else {
      ElMessage.error(data.msg);
      throw console.error(data.msg);
    }
  } else {
    ElMessage.warning(result.message);
    return;
  }
};

// TODO 开启确认关闭任务弹窗
const handleColseRequirement = (id: number) => {
  dialogCloseVisible.value = true;
  isRequirementID.value = id;
};


// 刷新fatherStatus
const updateFatherStatus = async (id: number) => {
  const { data } = await getNewFatherRequirementStatus({
    requirementId: id
  });

  if (data.code !== 200) {
    ElMessage.error(data.msg);
    return;
  }
};

// TODO 关闭未分配任务
const handleColse = async () => {
  const { data } = await putCloseRequirementStatus({
    requirementId: isAvgRequirementID.value
  });
  if ( data.code === 200) {
    dialogCloseVisible.value = false;
    loading.value = true;
    updateFatherStatus(isAvgRequirementID.value);
    getAllRequirements();
    loading.value = false;
  } else {
    dialogAvgVisible.value = false;
    ElMessage.error(data.msg);
    throw console.error(data.msg);
  }
};

// // 上线
// TODO 关闭上线结果弹窗
const handleCloseOnlineDialog = () => {
  // 清空上线结果数据
  offlineToEndForm.value = {
    requirementId: null,
    requirementOnlineStatus: 2,
    requirementOnlineMsg:""
  };
  offlineToEndFomrRef.value?.resetFields();
  dialogOfflineToEndVisible.value = false;
};

// TODO 关闭上线评分弹窗
const handleCloseOnlineContentDialog = () => {
  // 清空上线评语数据
  offlineToEndContentForm.value = [];
  isOnlineContent.value = true;
  dialogOfflineEndCotentVisible.value = false;
};


// TODO 开启上线评分弹窗
const handleOpenOfflineToEndContent = async (id: number) => {
  // 获取上线参与人内容
  const {data} =await GetGetBareUsersMsgs(id);
  if(data.code === 200) {
    if (userAuthId.value == '555') {
      offlineToEndContentForm.value = data.data.filter((item: any) => item.bearType == 1 || item.bearType == 3);
      console.log("参与上线任务内容：", offlineToEndContentForm.value);

      if (isRequirementData.value.tipDevOnlineStatus == 1) {
        isOnlineContent.value = true;
      } else {
        isOnlineContent.value = false;
      };

      dialogOfflineEndCotentVisible.value = true;
    } else if(userAuthId.value == '111') {
      offlineToEndContentForm.value = data.data.filter((item: any) => item.bearType == 2);
      console.log("参与上线任务内容：", offlineToEndContentForm.value);

      if (isRequirementData.value.tipTsOnlineStatus == 1) {
        isOnlineContent.value = true;
      } else {
        isOnlineContent.value = false;
      };

      dialogOfflineEndCotentVisible.value = true;
    }

  } else {
    ElMessage.error(data.msg);
    throw console.error(data.msg);
  }
};

// TODO 单选框变化事件
// const handleChangeOption = (val: string) => {
//   console.log("change：", val)
//   isOfflineToEnd.value = offlineToEndForm.value.requirementOnlineStatus == 3 ? true : false;
// };

// watch(offlineToEndForm.value.requirementOnlineStatus, (newValue, oldValue) => {
//   console.log(oldValue, newValue);
//   isOfflineToEnd.value = newValue;
// })

// TODO 提交上线结果
const handleSubmitOffline = async () => {
  isOfflineToEnd.value = offlineToEndForm.value.requirementOnlineStatus == 3 ? true : false;
  if (isOfflineToEnd.value) {
    if (offlineToEndForm.value.requirementOnlineMsg.trim() == '') {
      ElMessage.warning("请填写失败原因");
      return;
    } else {
      const {data} = await PostOfflineToEnd(offlineToEndForm.value);
      if(data.code === 200) {
        ElMessage.success(data.msg);
        await handleOpenOfflineToEndContent(isRequirementID.value);
        handleCloseOnlineDialog();

        loading.value = true;
        await getAllRequirements();
        loading.value = false; 

      } else {
        ElMessage.error(data.msg);
        throw console.error(data.msg);
      }
    }
  } else {
    const {data} = await PostOfflineToEnd(offlineToEndForm.value);
    if(data.code === 200) {
      ElMessage.success(data.msg);
      await handleOpenOfflineToEndContent(isRequirementID.value);
      handleCloseOnlineDialog();

      loading.value = true;
      await getAllRequirements();
      loading.value = false; 

    } else {
      ElMessage.error(data.msg);
      throw console.error(data.msg);
    }
  }


/*   console.log(offlineToEndForm.value.requirementOnlineMsg.trim())
  if(!formEl) {
    console.error("表单验证失败！");
    return;
  };

  const validatePromise = formEl.validate();
  try {
    await validatePromise;
    console.log("表单校验通过");

    // const {data} = await PostOfflineToEnd(offlineToEndForm.value);
    // if(data.code === 200) {
    //   ElMessage.success(data.msg);
    //   await handleOpenOfflineToEndContent(isRequirementID.value);
    //   handleCloseOnlineDialog();

    //   loading.value = true;
    //   await getAllRequirements();
    //   loading.value = false; 

    // } else {
    //   ElMessage.error(data.msg);
    //   throw console.error(data.msg);
    // }
  
  } catch(error) {
    ElMessage.error("表单校验失败");
    throw console.error(error);
  } */
};

// TODO 提交上线评论
const submitOnlineToEndForm = async () => {
    const submitData = offlineToEndContentForm.value.map((item: any) => {
      return {
        requirementBearId: item.ID,
        bearBossContent: item.bearBossContent,
        bearBossUserTPNumber: Number(item.bearBossUserTPNumber)
      }
    });
    console.log("提交评论：", submitData);

    const valid = submitData.every((item: any) => {
      // 校验是否有评语为空
      if(isValidateString(item.bearBossContent)) {
        ElMessage.error("每条评论都必填，且不能为空");
        return false;
      };

      // 校验评分是否为0-100之间的数字
      if(isNaN(item.bearBossUserTPNumber) || item.bearBossUserTPNumber < 0 || item.bearBossUserTPNumber > 100 || item.bearBossUserTPNumber == 0) {
        ElMessage.error("评分必须为(0~100]之间的数字,且不能为0");
        return false;
      };

      // 如果所有校验通过
      return true; 
    });

    console.log("校验结果：", valid);

    if(valid) {
      console.log("校验通过，提交评论");

      const {data} = await PutOnlineEndBearContents(submitData);
      if(data.code === 200) {
        ElMessage.success(data.msg);
        handleCloseOnlineContentDialog();
        loading.value = true;
        await getAllRequirements();
        loading.value = false;
      } else {
        ElMessage.error(data.msg);
        throw console.error(data.msg);
      }
    } else {
      console.log("每条记录必须有评语和评分；");
      return;
    }
};





onMounted(async () => {
  await useCommonStore.getAllRoleUsersList("");
  // getReviewNameOptions();
  getAllRequirements();
});
</script>

<style lang="scss" scoped>
.content-container {
  background-color: white;
  display: flex;
  flex-direction: column;
  padding: 10px;

  // TODO 搜索区域
  .search-wrap {
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #dcdfe6;

    .search-wrap-item {
      margin-right: 20px;
      min-width: 200px;
      font-weight: bold;
      font-size: 24px;
      font-family: Arial, Helvetica, sans-serif;
      color: #000;
    }
  };

  // 需求列表区域
  .card-layout-box {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;
    // justify-content: space-between;

    // 无数据时显示
    .card-not-requirement {
      color: #909399;
      margin: auto;
    }

    .card-box {
      // width: 100%;
      // width: 470px;
      width: 32%;
      height: 100%;
      height: 360px;
      border: 1px solid #909399;
      border-radius: 20px 20px 0 0;
      margin: 0 5px;
      display: flex;
      flex-direction: column;

      // margin: 0 10px 20px 0;
      // 列表标题
      .card-header-box {
        width: 100%;
        height: 40px;
        padding: 0 10px;
        line-height: 40px;
        font-size: 18px;
        font-family: Helvetica, Arial, sans-serif;
        color: white;
        border-radius: 20px 20px 0 0;
        display: flex;
        flex-direction: row;
      }

      // 列表盒子
      .card-list-box {
        width: 100%;
        height: calc(100% - 40px);
        display: flex;
        justify-content: start;
        overflow-y: auto;

        .card-list {
          width: 100%;
          height: 100%;
          font-size: 14px;
          overflow-y: auto;

          .card-list-item {
            width: 100%;
            display: flex;
            flex-direction: column;
            border-bottom: 1px solid #ccc;
            cursor: pointer;
            padding: 5px 5px;
            overflow: hidden;
            position: relative;

            // 附加信息样式
            .card-list-small {
              width: 100%;
              display: flex;
              justify-content: space-between;
              flex-direction: row;
              padding: 0;
              font-size: 0.7rem;
              white-space: nowrap;
              
              .card-small {
                width: 455px;
                display: flex;
                justify-content: space-between;
                flex-direction: row;
              }

              .card-list-small-item {
                margin: 0 10px 0 0;
              }

              // .item-status {
              //   width: 120px;
              // }

              .boss-name {
                width: 100px;
              }

              .test-list {
                width: 180px;
                overflow: hidden;
                text-overflow: ellipsis;
              }

              .begin-time {
                width: 110px;
              }

              .operate-box {
                width: 20px;
                text-align: right;
              }
            }

            // 操作按钮样式
            .card-list-operate {
              justify-content: flex-end;
              width: 60px;
              position: absolute;
              right: 10px;
              top: 2px;
              opacity: 1;
              z-index: 999;

              .el-col {
                margin: 1px 0;
                text-align: right;
              }
            }
          }

          .card-list-item:hover {
            background-color: rgb(216.8, 235.6, 255);
          }

          .card-header-title:hover {
            color: #409EFF;
          }
        }
      }
    }
  };

  // 审核需求
  .record-title {
    display: flex;
    flex-direction: row;
    padding: 5px 10px;
    margin-bottom: 10px;
    background-color: #f0f0f0;
    border-radius: 2px;
    p {
      margin-right: 20px;
    }
  }

  // 需求草稿
  .info-file-box {
      width: 100%;
      display: flex;
      justify-content: space-between;
      flex-direction: row;
      margin: 10px 0 0;
      .info-content-title {
          width: 100px;
          padding: 0 10px;
      }

      .info-file-ul {
          width: calc(100% - 70px);
          text-align: left;
          display: flex;
          flex-direction: row;
          .info-file-item {
              width: 60px;
              margin-right: 10px;
          }
          .info-file-item:hover {
              color: #409EFF;
              cursor: pointer;
          }
      }
  }

  // TODO 分配需求弹窗
  .dialog-container {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .dialog-form-title {
      font-weight: bold;
      padding: 10px;
      margin-bottom: 20px;
      background-color: #f0f0f0;
    }

    .dialog-form-box {
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: center;
      margin-bottom: 30px;

      .el-form-item {
        margin: 0 10px;
      }
    }

    .dialog-footer {
      width: 100%;
      text-align: right;
    }
  }

  // TODO 上线评分
  .dialog-online-container {
    margin-top: 20px;
    .online-box {
      width: 100%;
      display: flex;
      flex-direction: column;

      .online-form-box {
        width: 100%;
        max-height: 600px;
        overflow-y: auto;
        .online-form-ul>.online-form-li {
          border: 1px solid rgb(221.7, 222.6, 224.4);
          border-radius: 5px;
          margin-bottom: 10px;
          display: flex;
          flex-direction: column;
          padding: 10px;
          .online-form-content {
            width: 100%;
            display: flex;
            flex-direction: row;
            align-items: flex-start;
            .online-form-info {
              display: flex;
              flex-direction: row;
            }
            .online-form-info-left {
              width: 180px;
              margin-right: 20px;
            }
            .online-form-info-right {
              width: calc(100% - 200px);
              .online-info-title {
                width: 100px;
              }
            }
          }
          .online-form-content-top {
            margin-bottom: 10px;
          }
        }
      }
    
      .online-operate {
        width: 100%;
        text-align: right;
      }
    }
    // 上线结果
    .online-outcome {
      width: 100%;
      padding: 10px;
      border-radius: 5px;
      border: 1px solid rgb(221.7, 222.6, 224.4);
      margin-bottom: 10px;
      .online-outcome-top {
        margin-bottom: 10px;
      }
    }
  }
}
</style>
